import javax.swing.tree.TreeNode;
import java.util.Deque;
import java.util.LinkedList;
import java.util.Stack;

public class Test1 {
    public class TreeNode{
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode(){}
        TreeNode(int val){
            this.val = val;
        }
    }
    public boolean isSameTree(TreeNode p, TreeNode q) {
        Deque<TreeNode> deque1 = new LinkedList<>();
        Deque<TreeNode> deque2 = new LinkedList<>();
        Stack<TreeNode> stack1 = new Stack<>();
        Stack<TreeNode> stack2 = new Stack<>();
        deque1.offer(p);
        deque2.offer(q);

        while (p != null){
            TreeNode cur = deque1.poll();
            stack1.push(cur);
            deque1.offer(cur.left);
            deque2.offer(cur.right);
        }
        while (q != null){
            TreeNode cur = deque1.poll();
            stack2.push(cur);
            deque1.offer(cur.left);
            deque2.offer(cur.right);
        }
        if (stack1.size() == stack2.size()){
            for (int i = 0; i < stack1.size(); i++) {
                if (stack1.pop() == stack2.pop()){
                    continue;
                }else {
                    return false;
                }
            }
        }
        return false;
    }
}
